<template>
  <div class="enhanced-image-viewer">
    <el-card class="viewer-card">
      <template #header>
        <div class="card-header">
          <div class="header-info">
            <h2>DICOM图像查看器</h2>
            <el-tag v-if="metadata" :type="getModalityTagType(metadata.Modality)">
              {{ metadata.Modality }}
            </el-tag>
          </div>
          <div class="header-actions">
            <el-button @click="toggleFullscreen" :icon="isFullscreen ? 'Close' : 'FullScreen'" circle />
            <el-button @click="goBack" type="primary" plain>返回文件列表</el-button>
          </div>
        </div>
      </template>
      
      <div class="viewer-container">
        <!-- 左侧面板 - 元数据和帧列表 -->
        <div class="left-panel" :class="{ 'collapsed': !showMetadata }">
          <div class="panel-header">
            <h3>元数据信息</h3>
            <el-button @click="showMetadata = !showMetadata" link>
              <el-icon>{{ showMetadata ? 'ArrowLeft' : 'ArrowRight' }}</el-icon>
            </el-button>
          </div>
          
          <div v-if="showMetadata" class="metadata-content">
            <el-descriptions :column="1" size="small" border v-if="metadata">
              <el-descriptions-item label="患者ID">{{ metadata.PatientID }}</el-descriptions-item>
              <el-descriptions-item label="患者姓名">{{ metadata.PatientName }}</el-descriptions-item>
              <el-descriptions-item label="模态">{{ metadata.Modality }}</el-descriptions-item>
              <el-descriptions-item label="检查日期">{{ metadata.StudyDate }}</el-descriptions-item>
              <el-descriptions-item label="研究描述">{{ metadata.StudyDescription }}</el-descriptions-item>
            </el-descriptions>
            
            <div class="frame-list-container">
              <h3>帧列表 ({{ frameList.length }} 帧)</h3>
              <div class="frame-list">
                <div 
                  v-for="(frame, index) in frameList" 
                  :key="index"
                  class="frame-item"
                  :class="{ 'active': currentFrameIndex === index }"
                  @click="switchToFrame(index)"
                >
                  <div class="frame-thumbnail">
                    <el-image 
                      :src="frame.thumbnail" 
                      fit="cover" 
                      lazy
                      :preview-src-list="[frame.fullImage]"
                    >
                      <template #placeholder>
                        <div class="image-placeholder">
                          <el-icon><Picture /></el-icon>
                        </div>
                      </template>
                      <template #error>
                        <div class="image-error">
                          <el-icon><Picture /></el-icon>
                        </div>
                      </template>
                    </el-image>
                  </div>
                  <div class="frame-info">
                    <span class="frame-number">帧 {{ index + 1 }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 主显示区域 -->
        <div class="main-viewer">
          <!-- 图像显示区域 -->
          <div class="image-display-area">
            <div class="image-container">
              <div class="image-placeholder" v-if="!currentImage">
                <div class="placeholder-content">
                  <el-icon :size="48" color="#c0c4cc"><Picture /></el-icon>
                  <p class="placeholder-text">暂无图像数据</p>
                </div>
              </div>
              <el-image
                v-else
                :src="currentImage"
                class="main-image"
                fit="contain"
                :preview-src-list="[currentImage]"
                :initial-index="currentFrameIndex"
                @error="handleImageError"
              >
                <template #placeholder>
                  <div class="image-loading">
                    <el-icon :size="32" color="#409eff"><Loading /></el-icon>
                    <p>图像加载中...</p>
                  </div>
                </template>
              </el-image>
            </div>
          </div>
          
          <!-- 控制面板 -->
          <div class="control-panel">
            <div class="frame-info">
              <span>帧 {{ currentFrameIndex + 1 }} / {{ frameList.length }}</span>
            </div>
            
            <div class="playback-controls">
              <el-button @click="togglePlay" :icon="isPlaying ? 'VideoPause' : 'VideoPlay'" circle />
              <el-slider
                v-model="currentFrameIndex"
                :min="0"
                :max="frameList.length - 1"
                @change="onFrameChange"
                show-input
                show-input-controls
                :step="1"
              />
            </div>
            
            <div class="navigation-controls">
              <el-button @click="prevFrame" :disabled="currentFrameIndex <= 0" circle>
                <el-icon><ArrowLeft /></el-icon>
              </el-button>
              <el-button @click="nextFrame" :disabled="currentFrameIndex >= frameList.length - 1" circle>
                <el-icon><ArrowRight /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { 
  ElCard, 
  ElButton, 
  ElIcon, 
  ElImage, 
  ElSlider, 
  ElDescriptions, 
  ElDescriptionsItem,
  ElTag,
  ElMessage
} from 'element-plus'
import { 
  Picture, 
  ArrowLeft, 
  ArrowRight, 
  FullScreen,
  Close,
  VideoPlay,
  VideoPause,
  Loading
} from '@element-plus/icons-vue'
import api from '@/utils/api'

const route = useRoute()
const router = useRouter()

// 响应式数据
const filename = ref('')
const metadata = ref(null)
const frameList = ref([])
const currentFrameIndex = ref(0)
const currentImage = ref('')
const showMetadata = ref(true)
const isPlaying = ref(false)
const isFullscreen = ref(false)
const playInterval = ref(null)

// 获取模态类型标签类型
const getModalityTagType = (modality) => {
  const typeMap = {
    'US': 'success',
    'CT': 'warning',
    'MRI': 'primary',
    'CR': 'info',
    'DX': 'info'
  }
  return typeMap[modality] || 'info'
}

// 获取图像数据
const fetchImageData = async () => {
  try {
    filename.value = route.params.filename
    
    if (!filename.value) {
      ElMessage.error('未指定文件名')
      return
    }
    
    // 获取元数据
    const metadataResponse = await api.getDicomMetadata(filename.value)
    metadata.value = metadataResponse.data
    
    // 获取帧列表
    const framesResponse = await api.getDicomFrames(filename.value)
    frameList.value = framesResponse.data.map((frame, index) => ({
      ...frame,
      thumbnail: frame.path.replace('/dicom-img/', '/dicom-img/thumbnails/'),
      fullImage: frame.path
    }))
    
    // 初始化当前图像
    if (frameList.value.length > 0) {
      currentImage.value = frameList.value[0].fullImage
    }
  } catch (error) {
    ElMessage.error('获取图像数据失败: ' + error.message)
  }
}

// 切换到指定帧
const switchToFrame = (index) => {
  if (index >= 0 && index < frameList.value.length) {
    currentFrameIndex.value = index
    currentImage.value = frameList.value[index].fullImage
  }
}

// 帧变化处理
const onFrameChange = (value) => {
  switchToFrame(value)
}

// 上一帧
const prevFrame = () => {
  if (currentFrameIndex.value > 0) {
    switchToFrame(currentFrameIndex.value - 1)
  }
}

// 下一帧
const nextFrame = () => {
  if (currentFrameIndex.value < frameList.value.length - 1) {
    switchToFrame(currentFrameIndex.value + 1)
  }
}

// 切换播放状态
const togglePlay = () => {
  isPlaying.value = !isPlaying.value
  
  if (isPlaying.value) {
    startPlayback()
  } else {
    stopPlayback()
  }
}

// 开始播放
const startPlayback = () => {
  if (playInterval.value) {
    clearInterval(playInterval.value)
  }
  
  playInterval.value = setInterval(() => {
    if (currentFrameIndex.value < frameList.value.length - 1) {
      nextFrame()
    } else {
      // 播放完成，停止播放
      stopPlayback()
    }
  }, 200) // 每200ms切换一帧
}

// 停止播放
const stopPlayback = () => {
  isPlaying.value = false
  if (playInterval.value) {
    clearInterval(playInterval.value)
    playInterval.value = null
  }
}

// 处理图像加载错误
const handleImageError = (e) => {
  console.error('图像加载失败:', e)
  ElMessage.warning('图像加载失败，可能文件不存在')
}

// 切换全屏
const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value
  // 这里可以添加全屏切换的实现
  ElMessage.info('全屏功能待实现')
}

// 返回文件列表
const goBack = () => {
  router.push('/dicom-files')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchImageData()
})

// 组件卸载时清理
onUnmounted(() => {
  stopPlayback()
})
</script>

<style scoped>
.enhanced-image-viewer {
  padding: 20px;
  height: calc(100vh - 60px);
  background-color: #f5f5f5;
}

.viewer-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-info h2 {
  margin: 0;
  color: #303133;
}

.viewer-container {
  display: flex;
  flex: 1;
  overflow: hidden;
  gap: 20px;
}

.left-panel {
  width: 300px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.left-panel.collapsed {
  width: 40px;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
}

.metadata-content {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
}

.frame-list-container {
  margin-top: 20px;
}

.frame-list-container h3 {
  margin: 0 0 15px 0;
  font-size: 16px;
}

.frame-list {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
}

.frame-item {
  border: 2px solid transparent;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.frame-item:hover {
  border-color: #409eff;
}

.frame-item.active {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.frame-thumbnail {
  width: 100%;
  height: 60px;
  overflow: hidden;
  border-radius: 2px;
}

.frame-thumbnail :deep(.el-image) {
  width: 100%;
  height: 100%;
}

.frame-thumbnail :deep(.el-image__inner) {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-placeholder,
.image-error,
.image-loading {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
}

.image-loading p {
  margin: 5px 0 0 0;
  font-size: 12px;
  color: #909399;
}

.frame-info {
  text-align: center;
  padding: 5px 0;
  font-size: 12px;
  color: #606266;
}

.main-viewer {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.image-display-area {
  flex: 1;
  overflow: hidden;
  background-color: #000;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.main-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.control-panel {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 20px 0;
}

.frame-info {
  min-width: 100px;
  text-align: center;
  font-weight: bold;
  color: #303133;
}

.playback-controls {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 15px;
}

.navigation-controls {
  display: flex;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .left-panel {
    width: 250px;
  }
}

@media (max-width: 992px) {
  .viewer-container {
    flex-direction: column;
  }
  
  .left-panel {
    width: 100%;
    height: auto;
  }
  
  .control-panel {
    flex-wrap: wrap;
  }
  
  .playback-controls {
    order: 3;
    width: 100%;
    margin-top: 15px;
  }
}

@media (max-width: 768px) {
  .enhanced-image-viewer {
    padding: 10px;
  }
  
  .frame-list {
    grid-template-columns: repeat(4, 1fr);
  }
  
  .control-panel {
    gap: 10px;
  }
}
</style>